using DbContextDemo.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace DbContextDemo.Api.Controllers;

[ApiController]
[Route("[controller]")]
public class OrderController : ControllerBase
{
    private readonly AppDbContext _dbContext;

    public OrderController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpGet("{id}")]
    public async Task<Order?> GetAsync(int id)
    {
        return await _dbContext.Orders.AsNoTracking().FirstOrDefaultAsync(o => o.Id == id);
    }

    [HttpGet]
    public async Task<List<Order>> GetListAsync()
    {
        return await _dbContext.Orders.AsNoTracking().ToListAsync();
    }

    [HttpPost]
    public async Task<int> CreateAsync(string name)
    {
        var order = new Order()
        {
            Name = name,
            CreateDate = DateTime.UtcNow,
        };
        await _dbContext.Orders.AddAsync(order);
        await _dbContext.SaveChangesAsync();

        return order.Id;
    }

    [HttpPut("{id}")]
    public async Task<int> UpdateAsync(int id, string name)
    {
        var order = await _dbContext.Orders.FirstAsync(o=>o.Id == id);
        order.Name = name;
        await _dbContext.SaveChangesAsync();
        return order.Id;
    }

    [HttpDelete("{id}")]
    public async Task DeleteAsync(int id)
    {
        var order = await _dbContext.Orders.FirstAsync(o => o.Id == id);
        _dbContext.Orders.Remove(order);
        await _dbContext.SaveChangesAsync();
    }
}